package com.yshy.moviechoseseatingcommon.util;

import com.alibaba.fastjson.JSON;
import com.yshy.moviechoseseatingcommon.entity.vo.orders.NoticeCallbackBo;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author :
 * @desc :
 * @create: 下午7:04
 **/
public class Md5Util {
    public static String encrypt(String md5) {
        return DigestUtils.md5DigestAsHex(md5.getBytes(StandardCharsets.UTF_8));
    }

    public static String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return result;
    }


    /**
     * 验签
     */
    public static String checkSign(NoticeCallbackBo bo, String appKey, String secretKey) {

        Map<String, String> map = new TreeMap<>();
        map.put("appKey", appKey);
        map.put("orderNo", bo.getOrderNo());
        map.put("downOderNo", bo.getDownOderNo());
        map.put("eventType", bo.getEventType().toString());
        map.put("timestamp", bo.getTimestamp().toString());
        map.put("data", JSON.toJSONString(bo.getData()));

        StringBuffer sb = new StringBuffer();
        for (String s : map.keySet()) {
            sb.append(s + "=");
            sb.append(map.get(s) + "&");
        }
        sb.append("secretKey=" + secretKey);

        String sign = encrypt(sb.toString());
        return sign;
    }
}
